package com.yj.spring.beanPostProcessor;

import com.yj.spring.annotation.Autowired;
import com.yj.spring.charpter04.SimpleBeanFactory;

import java.lang.reflect.Field;

public class AutowiredBeanPostProcessor implements BeanPostProcessor {

    public SimpleBeanFactory simpleBeanFactory;

    public AutowiredBeanPostProcessor(SimpleBeanFactory simpleBeanFactory) {
        this.simpleBeanFactory = simpleBeanFactory;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {

        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (declaredField.isAnnotationPresent(Autowired.class)) {
                try {
                    declaredField.setAccessible(true);
                    String name = declaredField.getName();
                    Object injectBean = simpleBeanFactory.getBean(name);
                    declaredField.set(bean, injectBean);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        return null;
    }
}
